#encoding: utf-8 
require 'rubygems'
require 'uri'
require 'net/http'

namespace :db do
  namespace :links do
    def check_link(link)
      url = URI.parse link
      req = Net::HTTP.new(url.host, url.port)
      req.read_timeout = 5
      res = req.request_head(url.path)
      unless res.code == "200"
        puts "!!! invalid link #{link} !!!"
        return false
      end
      return true
    rescue
      puts "................ broken link #{link} \n"
      return false
    end

    def check_image(path)
      #puts Rails.root.to_s+"/public"+path
      File.exist?(Rails.root.to_s+"/public"+path)
    end

    task :check => :environment do
      puts "check movies ......"
      Video.find_all_by_kind('movie').each do |video|
        video.update_attributes :published => (check_link(video.link) and check_image(video.cover.url))
      end

      puts "check episode ......"
      Video.find_all_by_kind('episode').each do |video|
        video.update_attributes :published => check_image(video.cover.url)
        video.clips.each do |clip|
          clip.update_attributes :published => check_link(clip.link)
        end
      end
      
      puts "check tv ......"
      Video.find_all_by_kind('movie').each do |video|
        video.update_attributes :published => (check_link(video.link) and check_image(video.cover.url))
        video.clips.each do |clip|
          clip.update_attributes :published => (check_link(clip.link))
        end
      end
    end
  end
end
